package tgc.rj.zz.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.rj.zz.custom.DatagridFormUtils;
import tgc.rj.zz.custom.LogUtils;
import tgc.rj.zz.entity.Books;
import tgc.rj.zz.entity.Record;
import tgc.rj.zz.entity.Student;
import tgc.rj.zz.entity.SysUser;
import tgc.rj.zz.entity.Teacher;
import tgc.rj.zz.security.UserUtils;
import tgc.rj.zz.service.BooksService;
import tgc.rj.zz.service.RecordService;
import tgc.rj.zz.service.StudentService;
import tgc.rj.zz.service.TeacherService;

@Controller
@RequestMapping("/borrowed")
public class BorrowedController {

	@Autowired
	private UserUtils userUtils;
	@Autowired
	private StudentService stuDAO;
	@Autowired
	private RecordService recordDAO;
	@Autowired
	private BooksService bookDAO;
	@Autowired
	private TeacherService teacherDAO;
	@Autowired
	private LogUtils logUtils;
	/*
	 * 读者借书操作
	 */
	
	@RequestMapping("/borrowBook")
	@ResponseBody
	public String borrowBook(Integer id) {
		Books book = bookDAO.findById(id);
		Integer number = book.getNumber();
		if(number > 0) {
			SysUser user = userUtils.getUser();
			//查询用户的id
			Integer userid = user.getId();
			Record record = new Record();
			//图书数量减1
			Integer integer = number-1;
			book.setNumber(integer);
			bookDAO.save(book);
			record.setContactWay("手机号");
			if(user.getIdentity()==1) {
				Student stu = stuDAO.findById(userid);
				record.setBorrowedName(stu.getName());
				record.setContactPhone(stu.getPhone());
			}else {
				Teacher tea = teacherDAO.findById(userid);
				record.setBorrowedName(tea.getName());
				record.setContactPhone(tea.getPhone());
			}
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date = df.format(new Date());
			record.setDate(date);
			record.setAccredit("等待管理员确认");
			String title = book.getTitle();
			record.setBook(title);
			//借书人id
			record.setReader(user.getId());
			record.setBk(book);
			Date dtime = new Date();
			//结束日期60天（三个月）
			Date dt = stepDay(dtime , 60);
			record.setEndDate(df.format(dt));
			record.setDay(60);
			recordDAO.save(record);
			logUtils.log(user.getUsername(),user.getName(),"借了一本"+book.getTitle()+"书");
			return "借书提交发送成功，请等待管理员确认！";
		}else{
			return "此图书数量不足";
		}
	}
	private Date stepDay(Date dtime, int day) {
		Calendar instance = Calendar.getInstance();
		instance.setTime(dtime);
		//获取天数结束的日期
		instance.add(Calendar.DATE, day);
		return instance.getTime();
	}

	/*
	 * 读者借书信息和借书状态（等待管理员确认）
	 */
	@RequestMapping("/recordBorrow")
	public String recordBorrow(ModelMap map) {
		SysUser user = userUtils.getUser();
		Integer readerID = user.getId();
		List<Record> records = recordDAO.findByReaderAndAccredit(readerID,"等待管理员确认");
		map.put("records", records);
		return "borrowed/recordBorrow";
	}
	
	
	/*
	 * 图书授权页面
	 */
	@RequestMapping("/accredit")
	public String accredit() {
		return "borrowed/accredit";
	}
	
	/*
	 * 管理员图书授权
	 */
	@RequestMapping("/listAccredit")
	@ResponseBody
	public Object accredit(DatagridFormUtils custom) {
		Pageable pageable = custom.buildPageable();
		Page<Record> page = null;
		if(custom.getId()==null) {
			page = recordDAO.findAll(pageable);
		}else {
			page = recordDAO.findAll(custom.recordBuildSpec(), pageable);
		}
		HashMap<String, Object> pageResult = DatagridFormUtils.getPageResult(page);
		return pageResult;
		
	}
	/*
	 * 授权成功状态
	 */
	@RequestMapping("/acc")
	@ResponseBody
	public Object acc(Integer id) {
		Record record = recordDAO.findById(id);
		record.setAccredit("已借出");
		recordDAO.save(record);
		return "授权成功！";
	}
	
	/*
	 *读者还书操作
	 */
	@RequestMapping("/returnBook")
	public String returnBook(ModelMap map) {
		SysUser user = userUtils.getUser();
		Integer readerID = user.getId();
		List<Record> records = recordDAO.findByReaderAndAccredit(readerID,"已借出");
		map.put("records", records);
		return "borrowed/returnBook";
	}
	/*
	 *读者还书操作
	 */
	@RequestMapping("/hs")
	@ResponseBody
	public String hs(Integer id,Integer bk_id) {
		Record record = recordDAO.findById(id);
		Books books = bookDAO.findById(bk_id);
		Integer number = books.getNumber();
		Integer n = number+1;
		books.setNumber(n);
		bookDAO.save(books);
		record.setAccredit("已还");
		SysUser user = userUtils.getUser();
		logUtils.log(user.getUsername(),user.getName(),"还书");
		recordDAO.save(record);
		return "还书成功";
		
	}
	/*
	 *历史借书
	 */
	@RequestMapping("/historyBook")
	public String historyBook(ModelMap map) {
		SysUser user = userUtils.getUser();
		Integer readerID = user.getId();
		System.out.println(readerID);
		List<Record> records = recordDAO.findByReader(readerID);
		map.put("records", records);
		return "borrowed/historyBook";
	}
	/*
	 * 读者违约处理页面
	 */
	@RequestMapping("/breach")
	public String breach(ModelMap map){
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = df.format(new Date());
		List<Record> findAll = recordDAO.findByEndDateLessThanAndAccredit(date,"已借出");
		map.put("findAll", findAll);
		return "user/breach";
	}
	/*
	 * 读者违约解除限制
	 */
	@RequestMapping("/relieve")
	@ResponseBody
	public Object relieve(Integer id){
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		Record record = recordDAO.findById(id);
		String endDate = df.format(new Date());
		Calendar instance = Calendar.getInstance();
		Date endDate2;
		try {
			endDate2 = df.parse(endDate);
			instance.setTime(endDate2);
			instance.add(Calendar.DATE, 3);
			String format2 = df.format(instance.getTime());
			System.out.println("时间为"+format2);
			record.setEndDate(format2);
			recordDAO.save(record);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "成功加了3天时间";
	}
	
}
